<?php
// +----------------------------------------------------------------------
// | Redis 类
// +----------------------------------------------------------------------
// | 说明，任何为false的串，存在redis中都是空串。
// | 只有在key不存在时，才会返回false。
// | 这点可用于防止缓存穿透
// +----------------------------------------------------------------------

namespace extend\redis;


class Redis
{
    private $redis;

    // 实例化的对象,单例模式
    static private $_instance = array();

    public function __construct($config = [])
    {
        try {
            $this->redis = new \Redis();
            $host = $config['host'] ?? config('redis.host');
            $port = $config['port'] ?? config('redis.port');
            $timeout = $config['timeout'] ?? config('redis.timeout');
            $this->redis->connect($host, $port, $timeout);

            $password = $config['password'] ?? config('redis.password');
            $select = $config['select'] ?? config('redis.select');

            if (!empty($password)) {
                $this->redis->auth($password);
            }
            $result = $this->redis->select($select);
        } catch (\Exception $e) {
            throw new \Exception('REDIS服务异常');
        }

        if ($result == false) {
            throw new \Exception('REDIS链接错误');
        }
    }

    public static function instance($config = [])
    {
        if (!self::$_instance instanceof self) {
            self::$_instance = new self($config);
        }
        return self::$_instance;
    }

    public function __call($name, $args)
    {
        // ... 表示可变长度的变量
        $res = $this->redis->$name(...$args);
        return $res;
    }
}